﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace WindowsFormsThreadTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        public delegate void MyInvoke(string str);

        public delegate void MyInvoke1();


        Excuter _Excuter = new Excuter();

        private void button1_Click(object sender, EventArgs e)
        {

            Thread t1 = new Thread(new ThreadStart(T1));

            t1.Start();
        }

        private void T1()
        {
            for (int i = 0; i < 10; i++)
            {
                Set("T  " + i.ToString());

                Thread.Sleep(500);
            }
        }



        private void Set(string info)
        {
            if (listBox1.InvokeRequired)
            {
                MyInvoke _myInvoke = new MyInvoke(Set);
                this.Invoke(_myInvoke, info);
            }
            else
            {
                listBox1.Items.Add(info);
            }
        }

        private void button2_Click(object sender, EventArgs e)
        {
            List<MyClass> Clist = GetList();

            int i = Clist.Count;

            progressBar1.Maximum = i;
            
            progressBar1.Value = 0;

            _Excuter.ExcAll(Clist);

            //foreach (MyClass item in Clist)
            //{
            //    _Excuter.Exc(item.DoLongWork);
            //}

        }

        void item_Done(object sender, EventArgs e)
        {
            Set(sender.ToString()+"     Done");
            
            ShowProgress();
        }

        private void ShowProgress()
        {
            if (listBox1.InvokeRequired)
            {
                MyInvoke1 _myInvoke = new MyInvoke1(ShowProgress);
                this.Invoke(_myInvoke);
            }
            else
            {
                progressBar1.Value++;
            }
        }

        private List<MyClass> GetList()
        {
            List<MyClass> list = new List<MyClass>();

            for (int i = 0; i < 100; i++)
            {
                MyClass c = new MyClass() { ID = i, Name = "C" + i.ToString() };
                c.Done += new EventHandler(item_Done);
                list.Add(c);
            }

            return list;
        }

        private void button3_Click(object sender, EventArgs e)
        {
            _Excuter.Stop();
        }



       
    }
}
